package mua.core.value;

import java.util.ArrayList;
import java.util.HashMap;

import static mua.core.interpreter.Util.*;

public class FunctionBody extends MuaValue {
    ArrayList<MuaValue> arguments;
    String expression;
    //父亲，null即为全局变量
    FunctionBody name;
    //本地变量
    HashMap<String, MuaValue> localVariable = new HashMap<>();

    public FunctionBody(String str, FunctionBody functionBody){
        super();
        name = functionBody;
        value = str;
        //去除首尾"[]"
        String substring = str.substring(1,str.length()-1);

        //第一个中括号内的所有参数加入列表中
        int argumentIndex = substring.indexOf(']');
        String argumentString = substring.substring(substring.indexOf('['),argumentIndex+1);
        //list中定义了用空格分隔的string（首尾含"[]"）
        arguments = splitArguments(argumentString);
        expression = myTrim(substring.substring(argumentIndex+1));
    }

    private ArrayList<MuaValue> splitArguments(String argumentString) {
        ArrayList<MuaValue> list = new ArrayList<>();
        String temp = myTrim(argumentString).substring(1,argumentString.length()-1);
        String[] parts = split(temp);
        while(parts[0]!=null&&!parts[0].isEmpty()){
            list.add(judgeType(parts[0], this));
            parts = split(parts[1]);
        }
        return list;
    }

    public ArrayList<MuaValue> getArguments() {
        return arguments;
    }

    public String getExpression() {
        return expression;
    }

    public FunctionBody getName() {
        return name;
    }

    public HashMap<String, MuaValue> getLocalVariable() {
        return localVariable;
    }
}
